import time
import pymysql


class usersys_db:
    # 处理用户系统 与 数据库 之间的交互
    def __init__(self):
        self.db = pymysql.connect(
            user='test',  # 用户名
            password='test123',  # 密码
            host='192.168.0.125',  # 数据库ip
            port=3306,  # 数据库端口
            database="userinfo",  # 数据库名称
            charset='utf8mb4')  # 字符编码
        self.cs = self.db.cursor()

    def __del__(self):
        self.db.close()

    def have_uesr(self,usr):
        """判断是否有 指定用户, 有返回True， 没有返回False"""
        self.cs.execute(f"select * from user where uname = '{usr}'")
        data = self.cs.fetchall()
        if len(data) == 0:
            return False
        else:
            return True

    def add_user(self,usr,pwd):
        uid = int(time.time() * 1000000)
        try:
            self.cs.execute(f"insert into user values ({uid},'{usr}','{pwd}')")
            self.db.commit()
            print(f'新增用户{usr}成功.....')
        except BaseException as e:
            print('数据库异常.....')
            print('新增用户失败，请再次尝试.....')

    def get_user_pwd(self,usr):
        """传入用户名，返回 密码"""
        self.cs.execute(f"select upassword from user where uname = '{usr}'")
        data = self.cs.fetchall()
        return data[0][0]

    def change_user_pwd(self,usr,pwd):
        """修改密码"""
        self.cs.execute(f"update user set upassword = '{pwd}' where uname = '{usr}'")
        self.db.commit()
        print(f'用户{usr}的密码修改成功')

    def delete_user(self,usr):
        self.cs.execute(f"delete from user where uname = '{usr}';")
        self.db.commit()
        print(f'用户{usr}删除成功...')






